package com.tencent.sr.iris.activity.repository.config.single;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.github.pagehelper.PageInterceptor;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.tencent.sr.iris.activity.repository.singlemapper", sqlSessionTemplateRef = "singleSqlSessionTemplate")
public class SingleSourceConfig {

    @Bean(name = "singleDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource singleDataSource() {
        return new HikariDataSource();
    }

    @Bean(name = "singleSqlSessionFactory")
    public SqlSessionFactory singleSqlSessionFactory(@Qualifier("singleDataSource") DataSource dataSource)
            throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置single数据源mapper文件路径
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:singlemapper/*.xml"));

        PageInterceptor pageInterceptor = new PageInterceptor();
        bean.setPlugins(pageInterceptor);
        return bean.getObject();
    }

    @Bean(name = "singleTransactionManager")
    public DataSourceTransactionManager singleTransactionManager(@Qualifier("singleDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "singleSqlSessionTemplate")
    public SqlSessionTemplate singleSqlSessionTemplate(
            @Qualifier("singleSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
